<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>Modbus协议——ModbusRTU、ModbusASCII - 陈的错题集</title><meta name="Description" content="陈的错题集 - 个人笔记"><meta property="og:title" content="Modbus协议——ModbusRTU、ModbusASCII" />
<meta property="og:description" content="Modbus 是一项应用层报文传输协议，用于在通过不同类型的总线或网络连接的设备之间的客户机/服务器通信。常用于串口、以太网上的数据传输。 ADU：应用数" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://example.com/modbus/" /><meta property="og:image" content="https://example.com/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2023-08-23T20:02:41+08:00" />
<meta property="article:modified_time" content="2023-08-23T20:02:41+08:00" /><meta property="og:site_name" content="陈的错题集" />
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://example.com/logo.png"/>

<meta name="twitter:title" content="Modbus协议——ModbusRTU、ModbusASCII"/>
<meta name="twitter:description" content="Modbus 是一项应用层报文传输协议，用于在通过不同类型的总线或网络连接的设备之间的客户机/服务器通信。常用于串口、以太网上的数据传输。 ADU：应用数"/>
<meta name="application-name" content="陈的错题集">
<meta name="apple-mobile-web-app-title" content="陈的错题集"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://example.com/modbus/" /><link rel="prev" href="https://example.com/packml_05statusandadmintags/" /><link rel="next" href="https://example.com/modbustcp/" /><link rel="stylesheet" href="/css/style.min.css"><link rel="preload" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.1.1/css/all.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
        <noscript><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.1.1/css/all.min.css"></noscript><link rel="preload" href="https://cdn.jsdelivr.net/npm/animate.css@4.1.1/animate.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
        <noscript><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@4.1.1/animate.min.css"></noscript><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Modbus协议——ModbusRTU、ModbusASCII",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/example.com\/modbus\/"
        },"image": ["https:\/\/example.com\/images\/Apple-Devices-Preview.png"],"genre": "posts","keywords": "modbus","wordcount":  3069 ,
        "url": "https:\/\/example.com\/modbus\/","datePublished": "2023-08-23T20:02:41+08:00","dateModified": "2023-08-23T20:02:41+08:00","publisher": {
            "@type": "Organization",
            "name": "xxxx","logo": "https:\/\/example.com\/images\/avatar.png"},"author": {
                "@type": "Person",
                "name": "Jacob Chen"
            },"description": ""
    }
    </script></head>
    <body data-header-desktop="fixed" data-header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="陈的错题集">💻陈的错题集</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 📜归档 </a><a class="menu-item" href="/tags/"> 🏷️标签 </a><a class="menu-item" href="/categories/"> 📂分类 </a><a class="menu-item" href="/about/"> ⭐关于 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder=" " id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw" aria-hidden="true"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw" aria-hidden="true"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin" aria-hidden="true"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw" aria-hidden="true"></i>
                </a></div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="陈的错题集">💻陈的错题集</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder=" " id="search-input-mobile">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw" aria-hidden="true"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw" aria-hidden="true"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin" aria-hidden="true"></i>
                        </span>
                    </div>
                    <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">📜归档</a><a class="menu-item" href="/tags/" title="">🏷️标签</a><a class="menu-item" href="/categories/" title="">📂分类</a><a class="menu-item" href="/about/" title="">⭐关于</a><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                <i class="fas fa-adjust fa-fw" aria-hidden="true"></i>
            </a></div>
    </div>
</header><div class="search-dropdown desktop">
        <div id="search-dropdown-desktop"></div>
    </div>
    <div class="search-dropdown mobile">
        <div id="search-dropdown-mobile"></div>
    </div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animate__animated animate__flipInX">Modbus协议——ModbusRTU、ModbusASCII</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel="author" class="author"><i class="fas fa-user-circle fa-fw" aria-hidden="true"></i>Jacob Chen</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/%E9%80%9A%E8%AE%AF/"><i class="far fa-folder fa-fw" aria-hidden="true"></i>通讯</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw" aria-hidden="true"></i>&nbsp;<time datetime="2023-08-23">2023-08-23</time>&nbsp;<i class="fas fa-pencil-alt fa-fw" aria-hidden="true"></i>&nbsp;约 3069 字&nbsp;
                <i class="far fa-clock fa-fw" aria-hidden="true"></i>&nbsp;预计阅读 7 分钟&nbsp;</div>
        </div><div class="details toc" id="toc-static"  data-kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right" aria-hidden="true"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#串行通讯上的实现">串行通讯上的实现</a>
      <ul>
        <li><a href="#串口参数">串口参数</a></li>
        <li><a href="#传输模式">传输模式</a>
          <ul>
            <li><a href="#两种传输模式的不同点">两种传输模式的不同点</a></li>
          </ul>
        </li>
      </ul>
    </li>
    <li><a href="#modbus-rtu">Modbus-RTU</a>
      <ul>
        <li><a href="#数据帧格式">数据帧格式</a>
          <ul>
            <li><a href="#从站地址站号">从站地址（站号）</a></li>
            <li><a href="#功能码">功能码</a></li>
          </ul>
        </li>
        <li><a href="#功能码-0x03-命令格式解析">功能码 0x03 命令格式解析</a>
          <ul>
            <li><a href="#eg使用-功能码0x03-读取-站号01-地址0x00000x0009-的数据">eg.使用 功能码0x03 读取 站号01 地址0x0000~0x0009 的数据</a></li>
          </ul>
        </li>
        <li><a href="#功能码-0x10-命令格式解析">功能码 0x10 命令格式解析</a>
          <ul>
            <li><a href="#eg使用-功能码0x10-写入-站号01-地址0x00000x0009-的数据">eg.使用 功能码0x10 写入 站号01 地址0x0000~0x0009 的数据</a></li>
          </ul>
        </li>
        <li><a href="#crc校验">CRC校验</a>
          <ul>
            <li><a href="#移位法计算步骤"><strong>移位法</strong>计算步骤：</a></li>
          </ul>
        </li>
      </ul>
    </li>
    <li><a href="#modbus-ascii">Modbus-ASCII</a>
      <ul>
        <li><a href="#数据帧格式-1">数据帧格式</a>
          <ul>
            <li><a href="#eg使用-功能码0x03-读取-站号01-地址0x00000x0009-的数据-1">eg.使用 功能码0x03 读取 站号01 地址0x0000~0x0009 的数据</a></li>
          </ul>
        </li>
        <li><a href="#lrc校验">LRC校验</a>
          <ul>
            <li><a href="#lrc计算步骤">LRC计算步骤：</a></li>
            <li><a href="#使用命令字符对应的数字进行lrc计算">使用命令字符对应的数字进行LRC计算。</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><!-- # Modbus 协议 -->
<blockquote>
<p>Modbus 是一项应用层报文传输协议，用于在通过不同类型的总线或网络连接的设备之间的客户机/服务器通信。常用于串口、以太网上的数据传输。</p>
</blockquote>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gitee.com/jacobcj/blog-pic/raw/master/blog/Modbus%e5%b8%a7%e6%a0%bc%e5%bc%8f.png"
        data-srcset="https://gitee.com/jacobcj/blog-pic/raw/master/blog/Modbus%e5%b8%a7%e6%a0%bc%e5%bc%8f.png, https://gitee.com/jacobcj/blog-pic/raw/master/blog/Modbus%e5%b8%a7%e6%a0%bc%e5%bc%8f.png 1.5x, https://gitee.com/jacobcj/blog-pic/raw/master/blog/Modbus%e5%b8%a7%e6%a0%bc%e5%bc%8f.png 2x"
        data-sizes="auto"
        alt="https://gitee.com/jacobcj/blog-pic/raw/master/blog/Modbus帧格式.png"
        title="Modbus数据帧格式" /></p>
<ul>
<li><em>ADU：应用数据单元。最大不超过256个字节。一次Modbus通讯报文，可以被成为1个ADU。</em></li>
<li><em>PDU：协议数据单元。指代Modbus通讯报文中的 <strong>功能码 + 数据</strong></em></li>
</ul>
<h2 id="串行通讯上的实现">串行通讯上的实现</h2>
<blockquote>
<p>Modbus 串行链路协议是一个<strong>主/从协议</strong>。
<br/>常用物理接口为<strong>RS485、RS232、RS422</strong></p>
</blockquote>
<p>Modbus串行链路上所有设备的 <strong>串口参数</strong> 和 <strong>传输模式</strong> 必须相同。</p>
<h3 id="串口参数">串口参数</h3>
<table>
<thead>
<tr>
<th>参数名称</th>
<th>常见选项</th>
</tr>
</thead>
<tbody>
<tr>
<td>波特率</td>
<td>9600、19200、38400、115200 （单位：bps）</td>
</tr>
<tr>
<td>数据长度</td>
<td>8 、7 （单位：bit）</td>
</tr>
<tr>
<td>校验方式</td>
<td>偶校验（Even）、奇校验（Odd）、无校验（None）</td>
</tr>
<tr>
<td>停止位</td>
<td>1、2 （单位：bit）</td>
</tr>
</tbody>
</table>
<h3 id="传输模式">传输模式</h3>
<p>该协议在串口上2种传输模式：<strong>Modbus-RTU</strong> 和 <strong>Modbus-ASCII</strong>。</p>
<h4 id="两种传输模式的不同点">两种传输模式的不同点</h4>
<table>
<thead>
<tr>
<th></th>
<th>Modbus-RTU</th>
<th>Modbus-ASCII</th>
</tr>
</thead>
<tbody>
<tr>
<td>编码格式</td>
<td>二进制码</td>
<td>ASCII码</td>
</tr>
<tr>
<td>起始符</td>
<td>无</td>
<td>“冒号”（:）（ASCII码：0x3A）</td>
</tr>
<tr>
<td>结束符</td>
<td>无</td>
<td>“回车 + 换行”（CR LF）（ASCII码：0x0D、0x0A）</td>
</tr>
<tr>
<td>报文起停判断</td>
<td>时间间隔</td>
<td>起始符+结束符</td>
</tr>
<tr>
<td>校验方式</td>
<td>CRC</td>
<td>LRC</td>
</tr>
</tbody>
</table>
<h2 id="modbus-rtu">Modbus-RTU</h2>
<h3 id="数据帧格式">数据帧格式</h3>
<table>
<thead>
<tr>
<th>从站地址（站号）</th>
<th>功能码</th>
<th>数据</th>
<th>CRC校验</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 byte</td>
<td>1 byte</td>
<td>0~252 byte</td>
<td>2 byte</td>
</tr>
</tbody>
</table>
<h4 id="从站地址站号">从站地址（站号）</h4>
<table>
<thead>
<tr>
<th>广播地址</th>
<th>从站地址</th>
<th>保留</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1~247</td>
<td>248~255</td>
</tr>
</tbody>
</table>
<ul>
<li><strong>地址0</strong> 为广播地址。所有的子节点必须识别广播地址。（标准而已，并不是所有从站都完全遵照标准设计。在实际应用中较为少见）</li>
<li>Modbus<strong>主站没有节点地址</strong>，Modbus从站则必须拥有一个<strong>在串行链路上唯一的节点地址</strong>。</li>
</ul>
<h4 id="功能码">功能码</h4>
<table>
<thead>
<tr>
<th>功能描述</th>
<th>功能码（十进制）</th>
<th>功能码（十六进制）</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>读线圈</strong></td>
<td><strong>01</strong></td>
<td><strong>0x01</strong></td>
<td>常用</td>
</tr>
<tr>
<td>写单个线圈</td>
<td>05</td>
<td>0x05</td>
<td></td>
</tr>
<tr>
<td>写多个线圈</td>
<td>15</td>
<td>0x0F</td>
<td></td>
</tr>
<tr>
<td>读输入寄存器</td>
<td>04</td>
<td>0x04</td>
<td></td>
</tr>
<tr>
<td><strong>读保持寄存器</strong></td>
<td><strong>03</strong></td>
<td><strong>0x03</strong></td>
<td>常用</td>
</tr>
<tr>
<td>写单个保持寄存器</td>
<td>06</td>
<td>0x06</td>
<td></td>
</tr>
<tr>
<td><strong>写多个保持寄存器</strong></td>
<td><strong>16</strong></td>
<td><strong>0x10</strong></td>
<td>常用</td>
</tr>
<tr>
<td>读/写多个保持寄存器</td>
<td>23</td>
<td>0x17</td>
<td></td>
</tr>
</tbody>
</table>
<h3 id="功能码-0x03-命令格式解析">功能码 0x03 命令格式解析</h3>
<p>请求命令格式</p>
<table>
<thead>
<tr>
<th></th>
<th>大小</th>
<th>取值范围</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>从站地址</td>
<td>1 byte</td>
<td>0x01 至 0xFF</td>
<td></td>
</tr>
<tr>
<td>功能码</td>
<td>1 byte</td>
<td>0x03</td>
<td></td>
</tr>
<tr>
<td>起始地址</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
<td></td>
</tr>
<tr>
<td>寄存器数量（N）</td>
<td>2 byte</td>
<td>0x0000 至 0x007D</td>
<td></td>
</tr>
<tr>
<td>CRC校验</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
<td>所有数据的CRC校验</td>
</tr>
</tbody>
</table>
<p>响应命令格式</p>
<table>
<thead>
<tr>
<th></th>
<th>大小</th>
<th>取值范围</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>从站地址</td>
<td>1 byte</td>
<td>0x01 至 0xFF</td>
<td></td>
</tr>
<tr>
<td>功能码</td>
<td>1 byte</td>
<td>0x03</td>
<td></td>
</tr>
<tr>
<td>字节数</td>
<td>1 byte</td>
<td>2 * N</td>
<td>寄存器值所包括的字节数</td>
</tr>
<tr>
<td>寄存器值</td>
<td>2 * N byte</td>
<td>数据值</td>
<td>1个寄存器占用2个字节</td>
</tr>
<tr>
<td>CRC校验</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
<td>所有数据的CRC校验</td>
</tr>
</tbody>
</table>
<p><strong>注：<em>N = 寄存器数量</em></strong></p>
<p>错误响应格式</p>
<table>
<thead>
<tr>
<th></th>
<th>大小</th>
<th>取值范围</th>
</tr>
</thead>
<tbody>
<tr>
<td>从站地址</td>
<td>1 byte</td>
<td>0x01 至 0xFF</td>
</tr>
<tr>
<td>错误码</td>
<td>1 byte</td>
<td>0x83 <strong>（0x80 + 0x03）</strong></td>
</tr>
<tr>
<td>异常码</td>
<td>1 byte</td>
<td>0x01：该功能码不支持 <br/> 0x02：起始地址不支持 或者 起始地址+寄存器数量不支持 <br/> 0x03：读取寄存器数量不支持 <br/> 0x04：读取寄存器失败</td>
</tr>
<tr>
<td>CRC校验</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
</tr>
</tbody>
</table>
<h4 id="eg使用-功能码0x03-读取-站号01-地址0x00000x0009-的数据">eg.使用 功能码0x03 读取 站号01 地址0x0000~0x0009 的数据</h4>
<p>请求命令：SEND <strong>HEX</strong>&gt;<br/>
（站号）01 （功能码）03 （起始地址）00 00 （读取寄存器数量）00 0A （CRC校验）C5 CD</p>
<p>响应命令：RECV <strong>HEX</strong>&gt;<br/>
（站号）01 （功能码）03 （字节数）14 （读取的各个寄存器值）00 01 00 02 00 03 00 04 00 05 00 06 00 07 00 08 00 09 00 0A （CRC校验）8F 16</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave%e4%be%8b%e5%ad%9003.png"
        data-srcset="https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave%e4%be%8b%e5%ad%9003.png, https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave%e4%be%8b%e5%ad%9003.png 1.5x, https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave%e4%be%8b%e5%ad%9003.png 2x"
        data-sizes="auto"
        alt="https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave例子03.png"
        title="ModbusSlave03" /></p>
<h3 id="功能码-0x10-命令格式解析">功能码 0x10 命令格式解析</h3>
<p>请求命令格式</p>
<table>
<thead>
<tr>
<th></th>
<th>大小</th>
<th>取值范围</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>从站地址</td>
<td>1 byte</td>
<td>0x01 至 0xFF</td>
<td></td>
</tr>
<tr>
<td>功能码</td>
<td>1 byte</td>
<td>0x10</td>
<td></td>
</tr>
<tr>
<td>起始地址</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
<td></td>
</tr>
<tr>
<td>寄存器数量（N）</td>
<td>2 byte</td>
<td>0x0000 至 0x007D</td>
<td></td>
</tr>
<tr>
<td>字节数</td>
<td>1 byte</td>
<td>2 * N</td>
<td>寄存器值所包括的字节数</td>
</tr>
<tr>
<td>寄存器值</td>
<td>2 * N byte</td>
<td>数据值</td>
<td>1个寄存器占用2个字节</td>
</tr>
<tr>
<td>CRC校验</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
<td>所有数据的CRC校验</td>
</tr>
</tbody>
</table>
<p><strong>注：<em>N = 寄存器数量</em></strong></p>
<p>响应命令格式</p>
<table>
<thead>
<tr>
<th></th>
<th>大小</th>
<th>取值范围</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>从站地址</td>
<td>1 byte</td>
<td>0x01 至 0xFF</td>
<td></td>
</tr>
<tr>
<td>功能码</td>
<td>1 byte</td>
<td>0x03</td>
<td></td>
</tr>
<tr>
<td>起始地址</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
<td></td>
</tr>
<tr>
<td>寄存器数量（N）</td>
<td>2 byte</td>
<td>0x0000 至 0x007D</td>
<td></td>
</tr>
<tr>
<td>CRC校验</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
<td>所有数据的CRC校验</td>
</tr>
</tbody>
</table>
<p>错误响应格式</p>
<table>
<thead>
<tr>
<th></th>
<th>大小</th>
<th>取值范围</th>
</tr>
</thead>
<tbody>
<tr>
<td>从站地址</td>
<td>1 byte</td>
<td>0x01 至 0xFF</td>
</tr>
<tr>
<td>错误码</td>
<td>1 byte</td>
<td>0x90 <strong>（0x80 + 0x10）</strong></td>
</tr>
<tr>
<td>异常码</td>
<td>1 byte</td>
<td>0x01：该功能码不支持 <br/> 0x02：起始地址不支持 或者 起始地址+寄存器数量不支持 <br/> 0x03：读取寄存器数量不支持 <br/> 0x04：读取寄存器失败</td>
</tr>
<tr>
<td>CRC校验</td>
<td>2 byte</td>
<td>0x0000 至 0xFFFF</td>
</tr>
</tbody>
</table>
<h4 id="eg使用-功能码0x10-写入-站号01-地址0x00000x0009-的数据">eg.使用 功能码0x10 写入 站号01 地址0x0000~0x0009 的数据</h4>
<p>请求命令：SEND <strong>HEX</strong> &gt;<br/>
（站号）01 （功能码）10 （起始地址）00 00 （写入寄存器数量）00 0A （字节数）14 （各个寄存器的写入值）00 0A 00 14 00 1E 00 28 00 32 00 3C 00 46 00 50 00 5A 00 64 （CRC校验）69 8A</p>
<p>响应命令：RECV <strong>HEX</strong> &gt;<br/>
（站号）01 （功能码）10 （起始地址）00 00 （寄存器数量）00 0A （CRC校验）40 0E</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave%e4%be%8b%e5%ad%9010.png"
        data-srcset="https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave%e4%be%8b%e5%ad%9010.png, https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave%e4%be%8b%e5%ad%9010.png 1.5x, https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave%e4%be%8b%e5%ad%9010.png 2x"
        data-sizes="auto"
        alt="https://gitee.com/jacobcj/blog-pic/raw/master/blog/ModbusSlave例子10.png"
        title="ModbusSlave10" /></p>
<h3 id="crc校验">CRC校验</h3>
<blockquote>
<p>除了CRC校验码外的所有Modbus-RTU帧的数据，均需要进行CRC校验计算。</p>
</blockquote>
<h4 id="移位法计算步骤"><strong>移位法</strong>计算步骤：</h4>
<p>步骤一：加载一个内容为 0xFFFF 的 16位缓存器，称之为『CRC』缓存器。<br/>
步骤二：将需要计算的数据的第一个字节与 CRC 缓存器的低字节进行 异或运算（XOR），并将结果存回 CRC 缓存器。 <br/>
步骤三：检查 CRC 缓存器的最低位（LSB），若此位为 0，则右移一位；若此位为 1，则 CRC 缓存器值右移一位后，再与 0xA001 进行 异或运算（XOR）。 <br/>
步骤四：回到步骤三，直到步骤三已被执行过 8 次（即当前字节已经处理完），才进到步骤五。 <br/>
步骤五：对数据的下一个字节重复步骤二到步骤四，直到所有字节皆完全处理过，此时 CRC 缓存器的内容即是 CRC校验码。 <br/></p>
<p><strong>半查表法</strong></p>
<p>鉴于移位法、全查表法网上的资料已经太多了，这里介绍另外一种计算CRC校验码的方式。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-ST" data-lang="ST"><span class="line"><span class="cl"><span class="err">//</span><span class="nv">codesys3</span><span class="p">.</span><span class="m">5</span> <span class="nf">Structured</span> <span class="nf">Text</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nf">//</span>{<span class="nv">attribute</span> <span class="err">&#39;</span><span class="nf">hide_all_locals</span><span class="err">&#39;</span>}
</span></span><span class="line"><span class="cl"><span class="nf">FUNCTION</span> <span class="nf">F_CRC16</span> <span class="err">:</span> <span class="nf">WORD</span>
</span></span><span class="line"><span class="cl"><span class="nf">VAR_INPUT</span>
</span></span><span class="line"><span class="cl">	<span class="nf">pData</span>	<span class="err">:</span>	<span class="nf">POINTER</span> <span class="nf">TO</span> <span class="nf">BYTE</span>	<span class="p">;</span>	<span class="nf">//</span><span class="err">计算数据首字节的指针</span> <span class="nv">adr</span>(<span class="nv">data</span>)
</span></span><span class="line"><span class="cl">	<span class="nf">usiLen</span>	<span class="err">:</span>	<span class="nf">USINT</span>	<span class="p">;</span>	<span class="nf">//</span><span class="err">计算数据的长度</span>
</span></span><span class="line"><span class="cl"><span class="nf">END_VAR</span>
</span></span><span class="line"><span class="cl"><span class="nf">VAR</span>
</span></span><span class="line"><span class="cl">	<span class="nv">i</span>		<span class="err">:</span>	<span class="nf">USINT</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">temp</span>	<span class="err">:</span>	<span class="nf">BYTE</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">result</span>	<span class="err">:</span>	<span class="nf">WORD</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nf">END_VAR</span>
</span></span><span class="line"><span class="cl"><span class="nf">VAR</span> <span class="nf">CONSTANT</span>
</span></span><span class="line"><span class="cl">	<span class="nf">aTable</span>	<span class="err">:</span> <span class="nf">ARRAY</span>[<span class="m">0</span><span class="p">.</span>.<span class="m">15</span>] <span class="nf">OF</span> <span class="nf">WORD</span> <span class="o">:=</span>[<span class="m">16</span><span class="err">#</span><span class="nf">0</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">CC01,</span> <span class="m">16</span><span class="err">#</span><span class="nf">D801,</span> <span class="m">16</span><span class="err">#</span><span class="nf">1400</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">F001,</span> <span class="m">16</span><span class="err">#</span><span class="nf">3C00</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">2800</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">E401,</span> <span class="m">16</span><span class="err">#</span><span class="nf">A001,</span> <span class="m">16</span><span class="err">#</span><span class="nf">6C00</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">7800</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">B401,</span> <span class="m">16</span><span class="err">#</span><span class="nf">5000</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">9C01</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">8801</span><span class="err">,</span> <span class="m">16</span><span class="err">#</span><span class="nf">4400</span>]<span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nf">END_VAR</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nf">//</span><span class="err">半字节查表法计算CRC</span><span class="m">16</span>
</span></span><span class="line"><span class="cl"><span class="nf">result</span>	<span class="o">:=</span>	<span class="m">16</span><span class="err">#</span><span class="nf">FFFF</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nf">FOR</span> <span class="nf">i:</span><span class="err">=</span><span class="m">0</span> <span class="nf">TO</span> <span class="nf">usiLen-</span><span class="m">1</span> <span class="nf">BY</span> <span class="nf">1</span> <span class="nc">DO</span> 
</span></span><span class="line"><span class="cl">	<span class="nf">temp</span>	<span class="o">:=</span>	<span class="nc">TO_BYTE</span>((<span class="nv">result</span> <span class="nf">AND</span> <span class="nf">16</span><span class="ss">#000F</span>)) <span class="nf">XOR</span> (<span class="nv">pData</span><span class="err">^</span> <span class="nf">AND</span> <span class="nf">16</span><span class="ss">#0F</span>)	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">result</span>	<span class="o">:=</span>	<span class="nc">SHR</span>(<span class="nv">result</span><span class="nf">,</span> <span class="m">4</span>)	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">result</span>	<span class="o">:=</span>	<span class="nv">result</span> <span class="nf">XOR</span> <span class="nf">aTable</span>[<span class="nv">temp</span>]	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">temp</span>	<span class="o">:=</span>	<span class="nc">TO_BYTE</span>((<span class="nv">result</span> <span class="nf">AND</span> <span class="nf">16</span><span class="ss">#000F</span>)) <span class="nf">XOR</span> <span class="nf">SHR</span>(<span class="nv">pData</span><span class="err">^</span><span class="nf">,</span> <span class="m">4</span>)	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">result</span>	<span class="o">:=</span>	<span class="nc">SHR</span>(<span class="nv">result</span><span class="nf">,</span> <span class="m">4</span>)	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">result</span>	<span class="o">:=</span>	<span class="nv">result</span> <span class="nf">XOR</span> <span class="nf">aTable</span>[<span class="nv">temp</span>]	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">pData</span>	<span class="o">:=</span>	<span class="nv">pData</span> <span class="nf">+</span> <span class="m">1</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nf">END_FOR</span>
</span></span><span class="line"><span class="cl"><span class="nf">F_Crc16</span> <span class="o">:=</span> <span class="nv">result</span>	<span class="p">;</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="modbus-ascii">Modbus-ASCII</h2>
<h3 id="数据帧格式-1">数据帧格式</h3>
<table>
<thead>
<tr>
<th>起始字符</th>
<th>从站地址（站号）</th>
<th>功能码</th>
<th>数据</th>
<th>LRC校验</th>
<th>结束字符</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 byte <br/>冒号（：）</td>
<td>2 byte</td>
<td>2 byte</td>
<td>0~504（252*2） byte</td>
<td>2 byte</td>
<td>2 byte <br/>回车换行（CR LF）</td>
</tr>
</tbody>
</table>
<p>** 注：**</p>
<ul>
<li><em>ASCII数据项最大长度为252 * 2 个字节。是RTU的两倍</em></li>
<li>除了起始字符、结束字符，以及校验方式。其他项的数据是将RTU的报文直接翻译为十六进制数字对应的ASCII码，即0x01 翻译为 &lsquo;01&rsquo;(ASCII码：0x30、0x31)</li>
</ul>
<h4 id="eg使用-功能码0x03-读取-站号01-地址0x00000x0009-的数据-1">eg.使用 功能码0x03 读取 站号01 地址0x0000~0x0009 的数据</h4>
<p>请求命令：SEND <strong>ASCII</strong> &gt;<br/>
（冒号）:（站号）01（功能码）03（起始地址）0000（读取的寄存器数量）000A（LRC校验）F2（回车换行）CRLF</p>
<p>（对比）请求命令：SEND <strong>Hex</strong> &gt;<br/>
（冒号）0x3A（站号）0x30 0x31（功能码）0x30 0x33（起始地址）0x30 0x30 0x30 0x30（读取的寄存器数量）0x30 0x30 0x30 0x3A（LRC校验）0x41 0x32（回车换行）0x0D 0x0A</p>
<h3 id="lrc校验">LRC校验</h3>
<blockquote>
<p>除了起始字符、结束字符，以及LRC校验外的所有数据，均需要进行LRC校验计算。</p>
</blockquote>
<h4 id="lrc计算步骤">LRC计算步骤：</h4>
<p>步骤一：对需要校验的数据（2n个字符）两两组成一个16进制的数值求和。<br/>
步骤二：将求和结果与256求模。<br/>
步骤三：用256减去所得模值得到校验结果。（另一种方法：将模值按位取反然后加1）<br/></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-ST" data-lang="ST"><span class="line"><span class="cl"><span class="err">//</span><span class="nv">codesys3</span><span class="p">.</span><span class="m">5</span> <span class="nf">Structured</span> <span class="nf">Text</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nf">//</span>{<span class="nv">attribute</span> <span class="err">&#39;</span><span class="nf">hide_all_locals</span><span class="err">&#39;</span>}
</span></span><span class="line"><span class="cl"><span class="nf">FUNCTION</span> <span class="nf">F_LRC8</span> <span class="err">:</span> <span class="nf">BYTE</span>
</span></span><span class="line"><span class="cl"><span class="nf">VAR_INPUT</span>
</span></span><span class="line"><span class="cl">	<span class="nf">pData</span>	<span class="err">:</span>	<span class="nf">POINTER</span> <span class="nf">TO</span> <span class="nf">BYTE</span>	<span class="p">;</span>	<span class="nf">//</span><span class="err">计算数据首字节的指针</span> <span class="nv">adr</span>(<span class="nv">data</span>)
</span></span><span class="line"><span class="cl">	<span class="nf">usiLen</span>	<span class="err">:</span>	<span class="nf">USINT</span>	<span class="p">;</span>	<span class="nf">//</span><span class="err">计算数据的长度</span>
</span></span><span class="line"><span class="cl"><span class="nf">END_VAR</span>
</span></span><span class="line"><span class="cl"><span class="nf">VAR</span>
</span></span><span class="line"><span class="cl">	<span class="nv">i</span>		<span class="err">:</span>	<span class="nf">USINT</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">temp</span>	<span class="err">:</span>	<span class="nf">BYTE</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">result</span>	<span class="err">:</span>	<span class="nf">BYTE</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nf">END_VAR</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nf">FOR</span> <span class="nf">i:</span><span class="err">=</span><span class="m">0</span> <span class="nf">TO</span> <span class="nf">usiLen-</span><span class="m">1</span> <span class="nf">BY</span> <span class="nf">1</span> <span class="nc">DO</span> 
</span></span><span class="line"><span class="cl">	<span class="nf">result</span> 	<span class="o">:=</span>	<span class="nv">result</span> <span class="nf">+</span> <span class="nv">pData</span><span class="err">^</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="nf">pData</span>	<span class="o">:=</span>	<span class="nv">pData</span> <span class="nf">+</span> <span class="m">1</span>	<span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nf">END_FOR</span>
</span></span><span class="line"><span class="cl"><span class="nf">result</span>	<span class="o">:=</span> <span class="nc">TO_BYTE</span>(<span class="nv">result</span> <span class="nf">MOD</span> <span class="nf">16</span><span class="ss">#100</span>)	<span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nf">F_LRC8</span> <span class="o">:=</span> <span class="nc">TO_BYTE</span>(<span class="m">16</span><span class="err">#</span><span class="nf">100</span> <span class="err">-</span> <span class="nv">result</span>)	<span class="p">;</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="使用命令字符对应的数字进行lrc计算">使用命令字符对应的数字进行LRC计算。</h4>
<p>以请求命令（:01030000000AF2 CRLF）为例子说明：</p>
<p>需要进行LRC校验计算的数据为 01030000000A</p>
<p>另外一种LRC计算步骤如下：<br/>
步骤一：（累加）0+1+0+3+0+0+0+0+0+0+0+10 = 0xE （不是 30 + 31 &hellip; + 40 = 0x176）<br/>
步骤二：（FF减去步骤一累加值）0xFF - 0xE = 0xF1<br/>
步骤三：（步骤二值加1）0xF1 + 1 = 0xF2</p>
</div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2023-08-23</span>
            </div></div>
        <div class="post-info-line">
            <div class="post-info-md"><span>
                            <a class="link-to-markdown" href="/modbus/index.md" target="_blank">阅读原始文档</a>
                        </span></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw" aria-hidden="true"></i>&nbsp;<a href="/tags/modbus/">modbus</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/packml_05statusandadmintags/" class="prev" rel="prev" title="PackML从会到不会——状态、管理标签（5）"><i class="fas fa-angle-left fa-fw" aria-hidden="true"></i>PackML从会到不会——状态、管理标签（5）</a>
            <a href="/modbustcp/" class="next" rel="next" title="Modbus协议 —— ModbusTCP">Modbus协议 —— ModbusTCP<i class="fas fa-angle-right fa-fw" aria-hidden="true"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.115.4">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.11"><i class="far fa-kiss-wink-heart fa-fw" aria-hidden="true"></i> LoveIt</a>
                </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw" aria-hidden="true"></i><span itemprop="copyrightYear">2023 - 2024</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">Jacob Chen</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw" aria-hidden="true"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw" aria-hidden="true"></i>
            </a>
        </div><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.38.1/dist/autocomplete.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lunr@2.3.9/lunr.min.js"></script><script type="text/javascript" src="/lib/lunr/lunr.stemmer.support.min.js"></script><script type="text/javascript" src="/lib/lunr/lunr.zh.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lazysizes@5.3.2/lazysizes.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/clipboard@2.0.11/dist/clipboard.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":50},"comment":{},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":30,"type":"lunr"}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
